package com.yld.car.market;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import cn.yld.car.adapter.CarTypeAdapter;
import cn.yld.car.db.RecentlyViewedDBHelper;

import com.yld.car.common.ConstantUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.domain.Car;
import com.yld.car.domain.FilterCarInfo;
import com.yld.car.domain.SearchDetailCar;

public class CarTypeInfoActivity extends BaseActivity implements
		OnItemClickListener {

	private Button rightButton;
	private Button modelButton;

	private ListView carTypeList;

	private String id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		// 自定义标题栏
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.car_type);
		// 设置布局
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.custom_title_car);
		Intent i = getIntent();
		mBar = (ProgressBar) findViewById(R.id.progressBar);
		String name = i.getStringExtra("name");
		id = i.getStringExtra("carId");
		TextView titleText = ((TextView) findViewById(R.id.title));
		if (name != null) {
			titleText.setText(name);
		} else {
			titleText.setText("unkown");
			id = "1";
		}

		utils = NetworkProgressUtils.getInstance();
		super.onCreate(savedInstanceState);

		carTypeList = (ListView) findViewById(R.id.list1);
		showButton();
		this.rightButton = ((Button) findViewById(R.id.rightButton));
		this.rightButton.setVisibility(View.VISIBLE);
		this.rightButton.setText("筛选");
		this.rightButton.setOnClickListener(filterOnClickListener);
		this.rightButton.setClickable(true);

		carTypeList.setOnItemClickListener(this);
		new CarTypeTask().execute(new String[] { "", "", "" });
	}

	private ProgressBar mBar;
	private View.OnClickListener filterOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			Intent intent = new Intent();
			intent.setClass(CarTypeInfoActivity.this, FilterTypeActivity.class);
			startActivityForResult(intent, 1);

		}
	};

	private void showButton() {

		Button localButton = (Button) findViewById(R.id.leftButton);
		localButton.setVisibility(View.VISIBLE);

		localButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				finish();

			}
		});
	}

	private NetworkProgressUtils utils;

	private class CarTypeTask extends AsyncTask<String, String, ArrayList<Car>> {

		@Override
		protected ArrayList<Car> doInBackground(String... params) {

			/*
			 * 参数一：keyWords：点击某一个系列的ID或者是在搜索框输入的关键字
			 * 参数二：color：颜色，（数据列表页面右上角筛选按钮中的颜色，默认为空，参数值例如：“红”）
			 * 参数三：type：车辆类型，期货还是现货（数据列表页面右上角筛选按钮中的期现货，默认为空，参数值例如: “期货”
			 * 注意不能传入“美国期货”或者 “美国现货”）
			 * 参数四：port:港口名称，（数据列表页面右上角筛选按钮中的港口，默认为空，参数值例如：“张家港”） 参数五：flag:区别标示
			 * ，（参数值为“1”时：用户是通过点击某一个系列进入这个页面的，参数值为“2”时：通过在搜索框输入关键字进入这个页面的
			 * 注意：此参数要与keyWords相对应） 参数六：nowPage:当前页码，（参数值例如：“1”）
			 * 参数七：pageSize:每页显示条数，（参数值例如：“20”）
			 */

			HashMap<String, String> allParams = new HashMap<String, String>();
			allParams.put("keyWords", id);
			allParams.put("color", params[0]);
			allParams.put("type", params[1]);
			allParams.put("port", params[2]);
			allParams.put("flag", "1");
			allParams.put("nowPage", "1");
			allParams.put("pageSize", "20");
			Object o = utils.getWebservicesByData(
					ConstantUtils.NAME_SPACE,
					ConstantUtils.ALL_METHROD_NAME.get(6),
					ConstantUtils.NAME_SPACE
							+ ConstantUtils.ALL_METHROD_NAME.get(6),
					ConstantUtils.GET_PAGE_DATA_CARS_URL, allParams);

			// System.out.println(o);
			// System.out.println("=======================");
			ArrayList<Car> all = utils.parseJson(o.toString(), "table",
					NetworkProgressUtils.SEARCH_CAR_TYPE,true);

			// for (Car car : c) {
			//
			// if(car instanceof SearchDetailCar){
			//
			// SearchDetailCar s=(SearchDetailCar)car;
			// System.out.println(s);
			// }
			// }
			// System.out.println(c);
			return all;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			mBar.setVisibility(View.VISIBLE);
		}

		@Override
		protected void onPostExecute(ArrayList<Car> result) {

			super.onPostExecute(result);

			mBar.setVisibility(View.GONE);
			if (result != null) {

				CarTypeAdapter adapter = new CarTypeAdapter(result,
						CarTypeInfoActivity.this);
				carTypeList.setAdapter(adapter);
			}
		}

	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View v, int position,
			long id) {

		Object o = adapterView.getAdapter().getItem(position);

		if (o instanceof SearchDetailCar) {

			final SearchDetailCar s = (SearchDetailCar) o;
			new Thread(new Runnable() {

				/**
				 * { "recordcount":"1", --返回的数据条数 "table": [ { "no":"1", --序列号
				 * "id": "1683", --车辆ID "name": "外白内黑棕", --车辆外饰内饰简称，即这辆车的标题
				 * "classid": "111", --系列ID "press": "115", --价格（单位W） "qhtime":
				 * "2014-04-30", --到港时间（期货才有时间，现货没有时间即为空） "vin": "", --就是车架号
				 * "xppz": "运动包¤扩展真皮内饰¤红卡钳", --选配配置 "companyname": "",
				 * --这辆车所属经销商公司名称 "adddate": "2014-04-11 18:19:33", --这辆车的录入时间
				 * "pinpainame": "玛莎拉蒂", --此车品牌名称 "xiliename": "GHIBLI S Q4",
				 * --此车系列名称 "gangkouname": "张家港", --这辆车所属经销商公司所在港口 "xhorqh":
				 * "期货" --期货还是现货 } …… ] }
				 */
				@Override
				public void run() {
					SQLiteDatabase sqLiteDatabase = mApp.getmDbHelper()
							.getWritableDatabase();
					ContentValues values = new ContentValues();
					values.put(RecentlyViewedDBHelper.ID, s.getId());
					values.put(RecentlyViewedDBHelper.NO, s.getNo());
					values.put(RecentlyViewedDBHelper.NAME, s.getName());
					values.put(RecentlyViewedDBHelper.CLASS_ID, s.getClassid());
					values.put(RecentlyViewedDBHelper.PRESS, s.getPress());
					values.put(RecentlyViewedDBHelper.QHTIME, s.getQhtime());
					values.put(RecentlyViewedDBHelper.ADD_DATE, s.getAdddate());
					values.put(RecentlyViewedDBHelper.XPPZ, s.getXppz());
					values.put(RecentlyViewedDBHelper.COMPANY_NAME,
							s.getCompanyname());
					values.put(RecentlyViewedDBHelper.PIN_PAI_NAME,
							s.getPinpainame());
					values.put(RecentlyViewedDBHelper.XI_LIE_NAME,
							s.getXiliename());
					values.put(RecentlyViewedDBHelper.GANG_KOU_NAME,
							s.getGangkouname());
					values.put(RecentlyViewedDBHelper.XHORQH, s.getXhorgh());
					long rowId = sqLiteDatabase.insert(
							RecentlyViewedDBHelper.RECENT_VIEW_TABLE, null,
							values);
					if (rowId > 0) {
						System.out.println("insert------>插入成功。");
					} else {

						System.out.println("insert------>插入失败。");
					}

				}
			}).start();

			String cId = s.getId();
			Intent intent = new Intent();
			intent.putExtra("cId", cId);
			intent.putExtra("carName", s.getPinpainame());
			intent.putExtra("carType", s.getXhorgh());// 类型
			intent.putExtra("carSeries", s.getXiliename());

			intent.setClass(this, CarDetailInfoActivity.class);
			startActivity(intent);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (1 == requestCode && RESULT_OK == resultCode) {

			FilterCarInfo f = (FilterCarInfo) data
					.getSerializableExtra("filter");

			// System.out.println(s);
			new CarTypeTask().execute(new String[] { f.color, f.type, f.port });
		}
	}
}
